using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using ERP.Common.Results;
using ERP.ERPSystem.WarehouseManagement;
using ERP.ERPSystem.WarehouseManagement.Dto;
using ERP.Team.WarehouseManagement;
using Microsoft.Extensions.Logging;
using Volo.Abp.Application.Services;
using Volo.Abp.Domain.Repositories;
using Volo.Abp.Uow;

namespace ERP.Application.ERPSystem.WarehouseManagement
{
    /// <summary>
    /// 装箱管理服务实现
    /// </summary>
    public class PackingServices : ApplicationService, IPackingServices
    {
        private readonly IRepository<PackingModel, int> _packingRepository;

        public PackingServices(IRepository<PackingModel, int> packingRepository)
        {
            _packingRepository = packingRepository;
        }

        /// <summary>
        /// 获取装箱管理分页列表
        /// </summary>
        [UnitOfWork]
        public async Task<APIResult<PackingPagedResult>> GetPagedListAsync(PackingQueryDto query)
        {
            try
            {
                var queryable = await _packingRepository.GetQueryableAsync();

                // 应用搜索条件
                if (!string.IsNullOrEmpty(query.PackingCode))
                {
                    queryable = queryable.Where(x => x.PackingCode.Contains(query.PackingCode));
                }

                if (!string.IsNullOrEmpty(query.SaleOrderCode))
                {
                    queryable = queryable.Where(x => x.SaleOrderCode.Contains(query.SaleOrderCode));
                }

                if (!string.IsNullOrEmpty(query.InvoiceCode))
                {
                    queryable = queryable.Where(x => x.InvoiceCode.Contains(query.InvoiceCode));
                }

                if (!string.IsNullOrEmpty(query.CustomerCode))
                {
                    queryable = queryable.Where(x => x.CustomerCode.Contains(query.CustomerCode));
                }

                if (!string.IsNullOrEmpty(query.CustomerName))
                {
                    queryable = queryable.Where(x => x.CustomerName.Contains(query.CustomerName));
                }

                if (!string.IsNullOrEmpty(query.Inspector))
                {
                    queryable = queryable.Where(x => x.Inspector.Contains(query.Inspector));
                }

                if (query.State.HasValue)
                {
                    queryable = queryable.Where(x => x.State == query.State.Value);
                }

                if (query.StartPackingDate.HasValue)
                {
                    queryable = queryable.Where(x => x.PackingDate >= query.StartPackingDate.Value);
                }

                if (query.EndPackingDate.HasValue)
                {
                    queryable = queryable.Where(x => x.PackingDate <= query.EndPackingDate.Value);
                }

                // 获取总数
                var totalCount = queryable.Count();

                // 分页和排序
                var pagedData = queryable
                    .OrderByDescending(x => x.Id)
                    .Skip((query.PageNumber - 1) * query.PageSize)
                    .Take(query.PageSize)
                    .ToList();

                // 转换为DTO
                var pageData = pagedData.Select(entity => new PackingDto
                {
                    Id = entity.Id,
                    PackingCode = entity.PackingCode,
                    PackingDate = entity.PackingDate,
                    SaleOrderCode = entity.SaleOrderCode,
                    InvoiceCode = entity.InvoiceCode,
                    CustomerCode = entity.CustomerCode,
                    CustomerName = entity.CustomerName,
                    PackingLength = entity.PackingLength,
                    PackingWidth = entity.PackingWidth,
                    PackingHeight = entity.PackingHeight,
                    PackingSize = entity.PackingSize,
                    NetWeight = entity.NetWeight,
                    GrossWeight = entity.GrossWeight,
                    UnitWeight = entity.UnitWeight,
                    Inspector = entity.Inspector,
                    State = entity.State
                }).ToList();

                var result = new PackingPagedResult
                {
                    Items = pageData,
                    TotalCount = totalCount,
                    PageNumber = query.PageNumber,
                    PageSize = query.PageSize
                };

                return APIResult<PackingPagedResult>.CreateSuccess(result);
            }
            catch (Exception ex)
            {
                Logger.LogException(ex);
                return APIResult<PackingPagedResult>.CreateError("查询装箱管理列表失败");
            }
        }

        /// <summary>
        /// 根据ID获取装箱管理详情
        /// </summary>
        [UnitOfWork]
        public async Task<APIResult<PackingDto>> GetByIdAsync(int id)
        {
            try
            {
                var entity = await _packingRepository.GetAsync(id);
                if (entity == null)
                {
                    return APIResult<PackingDto>.CreateError("装箱管理不存在");
                }

                var result = new PackingDto
                {
                    Id = entity.Id,
                    PackingCode = entity.PackingCode,
                    PackingDate = entity.PackingDate,
                    SaleOrderCode = entity.SaleOrderCode,
                    InvoiceCode = entity.InvoiceCode,
                    CustomerCode = entity.CustomerCode,
                    CustomerName = entity.CustomerName,
                    PackingLength = entity.PackingLength,
                    PackingWidth = entity.PackingWidth,
                    PackingHeight = entity.PackingHeight,
                    PackingSize = entity.PackingSize,
                    NetWeight = entity.NetWeight,
                    GrossWeight = entity.GrossWeight,
                    UnitWeight = entity.UnitWeight,
                    Inspector = entity.Inspector,
                    State = entity.State
                };

                return APIResult<PackingDto>.CreateSuccess(result);
            }
            catch (Exception ex)
            {
                Logger.LogException(ex);
                return APIResult<PackingDto>.CreateError("获取装箱管理详情失败");
            }
        }

        /// <summary>
        /// 创建装箱管理
        /// </summary>
        [UnitOfWork]
        public async Task<APIResult<PackingDto>> CreateAsync(PackingCreateDto createDto)
        {
            try
            {
                // 检查装箱单编号是否重复
                var existingEntity = await _packingRepository.FirstOrDefaultAsync(x => x.PackingCode == createDto.PackingCode);
                if (existingEntity != null)
                {
                    return APIResult<PackingDto>.CreateError("装箱单编号已存在");
                }

                // 创建实体
                var entity = new PackingModel
                {
                    PackingCode = createDto.PackingCode,
                    PackingDate = createDto.PackingDate,
                    SaleOrderCode = createDto.SaleOrderCode ?? "",
                    InvoiceCode = createDto.InvoiceCode ?? "",
                    CustomerCode = createDto.CustomerCode ?? "",
                    CustomerName = createDto.CustomerName ?? "",
                    PackingLength = createDto.PackingLength ?? "",
                    PackingWidth = createDto.PackingWidth ?? "",
                    PackingHeight = createDto.PackingHeight ?? "",
                    PackingSize = createDto.PackingSize ?? "",
                    NetWeight = createDto.NetWeight ?? "",
                    GrossWeight = createDto.GrossWeight ?? "",
                    UnitWeight = createDto.UnitWeight ?? "",
                    Inspector = createDto.Inspector ?? "",
                    State = createDto.State
                };

                // 保存到数据库
                var savedEntity = await _packingRepository.InsertAsync(entity, autoSave: true);

                // 转换为DTO
                var result = new PackingDto
                {
                    Id = savedEntity.Id,
                    PackingCode = savedEntity.PackingCode,
                    PackingDate = savedEntity.PackingDate,
                    SaleOrderCode = savedEntity.SaleOrderCode,
                    InvoiceCode = savedEntity.InvoiceCode,
                    CustomerCode = savedEntity.CustomerCode,
                    CustomerName = savedEntity.CustomerName,
                    PackingLength = savedEntity.PackingLength,
                    PackingWidth = savedEntity.PackingWidth,
                    PackingHeight = savedEntity.PackingHeight,
                    PackingSize = savedEntity.PackingSize,
                    NetWeight = savedEntity.NetWeight,
                    GrossWeight = savedEntity.GrossWeight,
                    UnitWeight = savedEntity.UnitWeight,
                    Inspector = savedEntity.Inspector,
                    State = savedEntity.State
                };

                return APIResult<PackingDto>.CreateSuccess(result);
            }
            catch (Exception ex)
            {
                Logger.LogException(ex);
                return APIResult<PackingDto>.CreateError("创建装箱管理失败");
            }
        }

        /// <summary>
        /// 更新装箱管理
        /// </summary>
        [UnitOfWork]
        public async Task<APIResult<PackingDto>> UpdateAsync(PackingUpdateDto updateDto)
        {
            try
            {
                // 从数据库获取实体
                var entity = await _packingRepository.GetAsync(updateDto.Id);
                if (entity == null)
                {
                    return APIResult<PackingDto>.CreateError("装箱管理不存在");
                }

                // 检查装箱单编号是否被其他记录使用
                var existingEntity = await _packingRepository.FirstOrDefaultAsync(x => x.PackingCode == updateDto.PackingCode && x.Id != updateDto.Id);
                if (existingEntity != null)
                {
                    return APIResult<PackingDto>.CreateError("装箱单编号已被其他记录使用");
                }

                // 更新实体数据
                entity.PackingCode = updateDto.PackingCode;
                entity.PackingDate = updateDto.PackingDate;
                entity.SaleOrderCode = updateDto.SaleOrderCode ?? entity.SaleOrderCode;
                entity.InvoiceCode = updateDto.InvoiceCode ?? entity.InvoiceCode;
                entity.CustomerCode = updateDto.CustomerCode ?? entity.CustomerCode;
                entity.CustomerName = updateDto.CustomerName ?? entity.CustomerName;
                entity.PackingLength = updateDto.PackingLength ?? entity.PackingLength;
                entity.PackingWidth = updateDto.PackingWidth ?? entity.PackingWidth;
                entity.PackingHeight = updateDto.PackingHeight ?? entity.PackingHeight;
                entity.PackingSize = updateDto.PackingSize ?? entity.PackingSize;
                entity.NetWeight = updateDto.NetWeight ?? entity.NetWeight;
                entity.GrossWeight = updateDto.GrossWeight ?? entity.GrossWeight;
                entity.UnitWeight = updateDto.UnitWeight ?? entity.UnitWeight;
                entity.Inspector = updateDto.Inspector ?? entity.Inspector;
                entity.State = updateDto.State;

                try
                {
                    // 保存到数据库
                    var updatedEntity = await _packingRepository.UpdateAsync(entity, autoSave: true);

                    // 转换为DTO
                    var result = new PackingDto
                    {
                        Id = updatedEntity.Id,
                        PackingCode = updatedEntity.PackingCode,
                        PackingDate = updatedEntity.PackingDate,
                        SaleOrderCode = updatedEntity.SaleOrderCode,
                        InvoiceCode = updatedEntity.InvoiceCode,
                        CustomerCode = updatedEntity.CustomerCode,
                        CustomerName = updatedEntity.CustomerName,
                        PackingLength = updatedEntity.PackingLength,
                        PackingWidth = updatedEntity.PackingWidth,
                        PackingHeight = updatedEntity.PackingHeight,
                        PackingSize = updatedEntity.PackingSize,
                        NetWeight = updatedEntity.NetWeight,
                        GrossWeight = updatedEntity.GrossWeight,
                        UnitWeight = updatedEntity.UnitWeight,
                        Inspector = updatedEntity.Inspector,
                        State = updatedEntity.State
                    };

                    return APIResult<PackingDto>.CreateSuccess(result);
                }
                catch (Exception ex)
                {
                    Logger.LogError($"更新数据库时出错: {ex.Message}");
                    Logger.LogError($"异常详情: {ex}");
                    return APIResult<PackingDto>.CreateError("保存到数据库时出错");
                }
            }
            catch (Exception ex)
            {
                Logger.LogError($"更新装箱管理时出错: {ex.Message}");
                Logger.LogError($"异常详情: {ex}");
                return APIResult<PackingDto>.CreateError("更新装箱管理失败");
            }
        }

        /// <summary>
        /// 删除装箱管理
        /// </summary>
        [UnitOfWork]
        public async Task<OperationResult> DeleteAsync(int id)
        {
            try
            {
                // 从数据库删除
                await _packingRepository.DeleteAsync(id);
                return OperationResult.SuccessResult("删除成功");
            }
            catch (Exception ex)
            {
                Logger.LogException(ex);
                return OperationResult.ErrorResult("删除装箱管理失败");
            }
        }

        /// <summary>
        /// 批量删除装箱管理
        /// </summary>
        [UnitOfWork]
        public async Task<OperationResult> BatchDeleteAsync(List<int> ids)
        {
            try
            {
                if (ids == null || !ids.Any())
                {
                    return OperationResult.ErrorResult("请选择要删除的记录");
                }

                // 批量删除
                foreach (var id in ids)
                {
                    await _packingRepository.DeleteAsync(id);
                }

                return OperationResult.SuccessResult($"批量删除成功，共删除{ids.Count}条记录");
            }
            catch (Exception ex)
            {
                Logger.LogException(ex);
                return OperationResult.ErrorResult("批量删除装箱管理失败");
            }
        }
    }
} 